package com.sptpc.learnspring.controller;

import com.sptpc.learnspring.model.Category;
import com.sptpc.learnspring.service.ICategoryService;
import com.sptpc.learnspring.vo.CategoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;

    // 查询所有分类
    @GetMapping("/")
    public List<Category> getAllCategories() {
        // categoryService.reloadCategory();
        return categoryService.getAllCategories();
    }

    // 只查询分类信息
    @GetMapping("/{id}")
    public Category getCategory(@PathVariable("id") Long id) {
        return categoryService.getCategoryById(id);
    }

    // 添加新的饮品分类
    @PostMapping(value = "/add", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Category addNewCategory(@RequestBody Category newCategory) {
        // 插入数据
        categoryService.addCategory(newCategory);
        // 数据库更改后，使Category缓存失效，否则还会读取缓存
        categoryService.reloadCategory();
        return newCategory;
    }

    // 查询分类和其下面所有饮品
    @GetMapping("/{id}/a")
    public CategoryVO getCategoryWithDrinks(@PathVariable("id") Long id) {
        return categoryService.getCategoryWithDrinks(id);
    }

    // 更新饮品分类
    @PutMapping("/update")
    public Category updateCategory(@RequestBody Category updateCategory) {
        // 更新数据
        categoryService.updateCategory(updateCategory);
        // 数据库更改后，使Category缓存失效，否则还会读取缓存
        categoryService.reloadCategory();
        return updateCategory;
    }
}
